package com.example.music.Utils;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.example.music.Bean.LocalMusicBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MusicPlaylist {
    private List<LocalMusicBean> songs;
    private int currentSongIndex; // 当前播放音乐的位置
    private static MusicPlaylist instance;

    private MusicPlaylist() {
        songs = new ArrayList<>();
        currentSongIndex = -1; // 初始化为-1，表示没有正在播放的音乐
    }

    public static MusicPlaylist getInstance() {
        if (instance == null) {
            instance = new MusicPlaylist();
        }
        return instance;
    }

    public List<LocalMusicBean> getSongs() {
        return songs;
    }

    public int getCurrentSongIndex() {
        return currentSongIndex;
    }

    public void addSong(LocalMusicBean song) {
        songs.add(song);
    }

    public void removeSong(LocalMusicBean song) {
        songs.remove(song);
    }

    public void setCurrentSongIndex(int index) {
        currentSongIndex = index;
    }

    public void clearPlaylist() {
        songs.clear();
        currentSongIndex = -1;
    }

    public void updatePlaylist(Context context) {
        /* 加载本地存储当中的音乐mp3文件到集合当中*/
        // 1.获取ContentResolver对象
        ContentResolver resolver = context.getContentResolver();
        // 2.获取本地音乐存储的Uri地址
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        // 3 开始查询地址
        Cursor cursor = resolver.query(uri, null, null, null, null);

        // 4.遍历Cursor
        int id = 0;
        synchronized (instance) {
            while (cursor.moveToNext()) {
                String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                id++;
                String sid = String.valueOf(id);
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
                String time = sdf.format(new Date(duration));
                // 获取专辑图片主要是通过album_id进行查询
                String album_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                String albumArt = "";
                // 将一行当中的数据封装到对象当中
                LocalMusicBean bean = new LocalMusicBean(sid, song, singer, album, time, path, albumArt);
                instance.addSong(bean);
            }
        }
    }
}